GBML manual / Lists

list_sort_by

Puts the items of target in order by a number YOU work out for each one. key is the NAME of one of your scripts; it takes one argument (the item) and gives back a number. With ascending true the item with the smallest number comes first; with false the biggest first. Unlike list_sort it works on lists of structs and references, so "nearest enemy first" or "highest score first" is one line: list_sort_by(enemies, distance_to_player, true).

Syntax

list_sort_by(target, key, ascending)

Arguments

NameType
targetlist
keyscript
ascendingbool

Returns

Nothing.

Description

Puts the items of target, a list, in order by a number you work out for each one. key is the name of one of your scripts. It is handed one item and gives back a number. With ascending true the item with the smallest number comes first; with false the biggest comes first.

Unlike list_sort, it works on lists of structs and references, because only the number the script gives is compared. So "nearest enemy first" or "highest score first" is one line:

list_sort_by(enemies, distance_to_player, true);

The script

The script takes exactly one parameter, which is where each item arrives, and gives back a whole number or a decimal:

// scripts/distance_to_player.gbml
function distance_to_player(e): real {
    return dist_to(x, y, e.x, e.y);
}

You can also write the function right where the name goes: list_sort_by(scores, function (n) { return 0 - n; }, true).

Example

/// @type {list<int>}
var scores = [30, 80, 55, 10];
list_sort_by(scores, by_value, true);    // 10, 30, 55, 80
list_sort_by(scores, by_value, false);   // 80, 55, 30, 10

The key script by_value gives back the item itself, so this sorts like list_sort would. A script that gives back something else sorts by that instead.

The small print

Cost

An insertion sort in place; the script runs for every comparison.

On the GBA

An insertion sort done in place, no copy and no extra memory. It is stable: items whose numbers are equal stay in the order they were in. The key script is called once for each item that is moved into place and once for each comparison, so about n times n over four calls for a list in random order - fine for a few dozen items, something to avoid every frame for hundreds. The script must give back a whole number or a decimal (anything else is refused when the project is checked). Do not add to or take from target inside the script. Text is not compared here, only the numbers the script gives. Lists only; an array or a grid cannot be sorted this way.

See also: list_sortlist_minlist_maxlist_foreachlist_shuffleListsScriptsData containers